package org.xinjiang.tarim.travel.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xinjiang.tarim.travel.model.File;
import org.xinjiang.tarim.travel.model.Impression;
import org.xinjiang.tarim.travel.model.Topic;
import org.xinjiang.tarim.travel.service.ImpressionService;
import org.xinjiang.tarim.travel.utils.Constants;
import org.xinjiang.tarim.travel.utils.HttpRequest;
import org.xinjiang.tarim.travel.utils.JsonResult;
import org.xinjiang.tarim.travel.utils.SensitiveWord;
import org.xinjiang.tarim.travel.vo.Criteria;
import org.xinjiang.tarim.travel.vo.PageBean;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/impression")
public class ImpressionApi {
    @Autowired
    ImpressionService impressionService;

    private static String KEY = "4IUBZ-LDUWF-SCVJP-JYV6W-D3VEJ-OHF67";

    private static String NEARBY_KEYWORD = "景点";

    private static String REGION = "新疆";

    @RequestMapping(value = "/getNearby")
    public JsonResult getNearby(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                @RequestParam(value = "lat") String lat,
                                @RequestParam(value = "lng") String lng) {
        JsonResult jsonResult;
        PageBean pageBean = new PageBean(pageIndex, pageSize);

        String url = "https://apis.map.qq.com/ws/place/v1/search";

        String param = "boundary=nearby(" + lat + "," + lng + ",1000)" +
                "&keyword=" + NEARBY_KEYWORD +
                "&page_size=" + pageSize +
                "&page_index=" + pageIndex +
                "&orderby=_distance" +
                "&key=" + KEY;
        String obj = HttpRequest.sendGet(url, param);
        JSONObject json = JSON.parseObject(obj);

        pageBean.setTotalCount(Long.valueOf(json.get("count").toString()));
        pageBean.setResultList(JSONArray.parseArray(json.get("data").toString(), Map.class));
        jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "查询成功", pageBean);
        return jsonResult;
    }

    @RequestMapping(value = "/searchPlace")
    public JsonResult searchPlace(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                  @RequestParam(value = "lat") String lat,
                                  @RequestParam(value = "lng") String lng,
                                  @RequestParam(value = "keyword") String keyword) {
        JsonResult jsonResult;
        PageBean pageBean = new PageBean(pageIndex, pageSize);

        String url = "https://apis.map.qq.com/ws/place/v1/suggestion";
        String param = "keyword=" + keyword +
                "&region=" + REGION +
                "&location=" + lat + "," + lng +
                "&page_size=" + pageSize +
                "&page_index=" + pageIndex +
                "&key=" + KEY;
        String obj = HttpRequest.sendGet(url, param);
        JSONObject json = JSON.parseObject(obj);
        List<JSONObject> list = JSONArray.parseArray(json.get("data").toString(), JSONObject.class);
        for (JSONObject map : list) {
            Map map1 = new HashMap();
            map1.put("district", map.get("district") == null ? "" : map.get("district").toString());
            map1.put("city", map.get("city") == null ? "" : map.get("city").toString());
            map1.put("province", map.get("province") == null ? "" : map.get("province").toString());
            map.put("ad_info", map1);
        }
        pageBean.setTotalCount(Long.valueOf(json.get("count").toString()));
        pageBean.setResultList(list);
        jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "查询成功", pageBean);
        return jsonResult;
    }

    /**
     * 发布印象
     * @param request
     * @param param
     * @return
     */
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public JsonResult insert(HttpServletRequest request, @RequestBody String param) {
        SensitiveWord sensitiveWord = new SensitiveWord();
        sensitiveWord.InitializationWork();
        JsonResult jsonResult;
        String openid = request.getHeader("tokenId");
        Map map = JSON.parseObject(param, Map.class);
        map = JSON.parseObject(map.get("param").toString(), Map.class);
        Impression impression = JSON.parseObject(JSON.toJSONString(map.get("impression")), Impression.class);
        impression.setContent(sensitiveWord.filterInfo(impression.getContent()));
        List<File> fileList = JSONArray.parseArray(JSON.toJSONString(map.get("files")), File.class);
        List<Topic> topicList = JSONArray.parseArray(JSON.toJSONString(map.get("topics")), Topic.class);
        impression.setOpenid(openid);

        Long impressionId = impressionService.insert(impression, fileList, topicList);
        if(impressionId != null){
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "发布成功", impressionId);
        }else {
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "发布失败，请联系管理员");
        }
        return jsonResult;
    }

    /**
     * 查询用户发布的印象
     * @param request
     * @return
     */
    @RequestMapping(value = "/select")
    public JsonResult selectByUser(HttpServletRequest request,
                                   @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        JsonResult jsonResult;
        try {
            PageBean pageBean = new PageBean(pageIndex, pageSize);
            String openid = request.getHeader("tokenId");
            Criteria criteria = new Criteria();
            criteria.addExtField("openid", openid);
            pageBean = impressionService.selectByOpenid(criteria, pageBean);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "查询成功", pageBean);
        }catch (Exception e){
            e.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "查询异常");
        }
        return jsonResult;
    }

    /**
     * 删除印象
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete")
    public JsonResult delete(Long id){
        JsonResult jsonResult;
        try {
            int i = impressionService.delete(id);
            if(i == 1){
                jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "删除成功");
            }else{
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "删除失败");
            }
        }catch (Exception e){
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "删除异常");
        }
        return jsonResult;
    }

    /**
     * 获取印象详情
     * @param impressionId
     * @return
     */
    @RequestMapping(value = "/getDetail")
    public JsonResult getDetail(Long impressionId){
        JsonResult jsonResult;
        try {
            Map map = impressionService.selectByPrimaryKey(impressionId);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "获取成功", map);
        }catch (Exception e){
            e.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "获取异常");
        }
        return jsonResult;
    }

}
